<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>消息中心</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="markAllAsRead">
          全部标记为已读
        </el-button>
      </div>

      <el-tabs v-model="activeTab">
        <!-- 全部消息 -->
        <el-tab-pane label="全部消息" name="all">
          <message-list
            :messages="filteredMessages"
            :total="total"
            :current-page="currentPage"
            :page-size="pageSize"
            @read="handleMarkAsRead"
            @delete="handleDelete"
            @page-change="handlePageChange"/>
        </el-tab-pane>

        <!-- 系统消息 -->
        <el-tab-pane label="系统消息" name="system">
          <message-list
            :messages="systemMessages"
            :total="systemTotal"
            :current-page="currentPage"
            :page-size="pageSize"
            @read="handleMarkAsRead"
            @delete="handleDelete"
            @page-change="handlePageChange"/>
        </el-tab-pane>

        <!-- 私信 -->
        <el-tab-pane label="私信" name="private">
          <message-list
            :messages="privateMessages"
            :total="privateTotal"
            :current-page="currentPage"
            :page-size="pageSize"
            @read="handleMarkAsRead"
            @delete="handleDelete"
            @page-change="handlePageChange"/>
        </el-tab-pane>

        <!-- 互动通知 -->
        <el-tab-pane label="互动通知" name="interaction">
          <message-list
            :messages="interactionMessages"
            :total="interactionTotal"
            :current-page="currentPage"
            :page-size="pageSize"
            @read="handleMarkAsRead"
            @delete="handleDelete"
            @page-change="handlePageChange"/>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import MessageList from './components/MessageList'
import request from '@/utils/request'
import { mapGetters } from 'vuex'

export default {
  name: 'MessageCenter',
  components: { MessageList },
  data() {
    return {
      activeTab: 'all',
      messages: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      systemTotal: 0,
      privateTotal: 0,
      interactionTotal: 0
    }
  },
  computed: {
    ...mapGetters([
      'userId'
    ]),
    // 过滤后的消息列表
    filteredMessages() {
      return this.messages
    },
    // 系统消息
    systemMessages() {
      return this.messages.filter(msg => msg.type === 'system')
    },
    // 私信
    privateMessages() {
      return this.messages.filter(msg => msg.type === 'private')
    },
    // 互动通知（点赞、评论等）
    interactionMessages() {
      return this.messages.filter(msg => ['like', 'comment', 'reply', 'favorite'].includes(msg.type))
    }
  },
  created() {
    this.getMessages()
  },
  watch: {
    activeTab: {
      handler(newVal) {
        this.currentPage = 1 // 切换标签时重置页码
        this.getMessages()
      }
    }
  },
  methods: {
    // 获取消息列表
    async getMessages() {
      try {
        // 确保userId存在且有效
        if (!this.userId) {
          console.error('用户ID未定义，无法获取消息');
          this.$message.error('用户信息未加载完成，请稍后重试');
          this.messages = [];
          this.total = 0;
          return;
        }

        let url = `/api/message/list/${this.userId}`;
        let params = {
          page: this.currentPage - 1, // 后端页码从0开始
          size: this.pageSize
        };
        
        // 如果选择了特定标签，添加type参数
        if (this.activeTab === 'system') {
          params.type = 'system';
        } else if (this.activeTab === 'private') {
          params.type = 'private';
        } else if (this.activeTab === 'interaction') {
          params.types = 'like,comment,reply,favorite';
        }
        
        const response = await request({
          url: url,
          method: 'get',
          params: params
        });
        
        console.log('消息列表响应:', response);
        
        // 统一解析响应格式
        if (response) {
          let messages = [];
          let total = 0;
          
          // 检查错误响应
          if (response.error) {
            console.error('获取消息出错:', response.message);
            this.$message.error(response.message || '获取消息失败');
            this.messages = [];
            this.total = 0;
            return;
          }
          
          if (Array.isArray(response)) {
            // 直接是数组格式
            messages = response;
            total = response.length;
          } else if (response.messages || response.rows || response.content) {
            // 分页对象格式
            messages = response.messages || response.rows || response.content || [];
            total = response.totalItems || response.total || response.totalElements || messages.length;
          } else if (response.data) {
            // 包装在data字段中
            if (Array.isArray(response.data)) {
              messages = response.data;
              total = response.data.length;
            } else {
              messages = response.data.content || response.data.list || response.data.records || [];
              total = response.data.totalElements || response.data.total || messages.length;
            }
          }
          
          this.messages = messages;
          this.total = total;
          
          // 更新各类型消息的总数
          this.systemTotal = this.messages.filter(msg => msg.type === 'system').length;
          this.privateTotal = this.messages.filter(msg => msg.type === 'private').length;
          this.interactionTotal = this.messages.filter(msg => 
            ['like', 'comment', 'reply', 'favorite'].includes(msg.type)).length;
            
          console.log('处理后的消息数据:', {
            total: this.total,
            systemTotal: this.systemTotal,
            privateTotal: this.privateTotal,
            interactionTotal: this.interactionTotal
          });
        } else {
          console.warn('未找到消息数据:', response);
          this.messages = [];
          this.total = 0;
          this.systemTotal = 0;
          this.privateTotal = 0;
          this.interactionTotal = 0;
        }
      } catch (error) {
        console.error('获取消息列表失败:', error);
        this.$message.error('获取消息列表失败');
        this.messages = [];
        this.total = 0;
      }
    },
    // 处理页码变化
    handlePageChange(page) {
      this.currentPage = page
      this.getMessages()
    },
    // 标记消息为已读
    async handleMarkAsRead(messageId) {
      try {
        // 确保userId存在且有效
        if (!this.userId) {
          console.error('用户ID未定义，无法标记消息');
          this.$message.error('用户信息未加载完成，请稍后重试');
          return;
        }

        await request({
          url: `/api/message/${messageId}/read`,
          method: 'put',
          params: {
            userId: this.userId
          }
        })
        // 更新本地消息状态
        const message = this.messages.find(m => m.id === messageId)
        if (message) {
          message.isRead = true
        }
        this.$message.success('已标记为已读')
      } catch (error) {
        console.error('标记已读失败:', error)
        this.$message.error('标记已读失败')
      }
    },
    // 删除消息
    async handleDelete(messageId) {
      try {
        // 确保userId存在且有效
        if (!this.userId) {
          console.error('用户ID未定义，无法删除消息');
          this.$message.error('用户信息未加载完成，请稍后重试');
          return;
        }

        await request({
          url: `/api/message/${messageId}`,
          method: 'delete',
          params: {
            userId: this.userId
          }
        })
        // 从本地列表中移除消息
        this.messages = this.messages.filter(m => m.id !== messageId)
        
        // 更新各类型消息的总数
        this.total = Math.max(0, this.total - 1);
        this.systemTotal = this.messages.filter(msg => msg.type === 'system').length;
        this.privateTotal = this.messages.filter(msg => msg.type === 'private').length;
        this.interactionTotal = this.messages.filter(msg => 
          ['like', 'comment', 'reply', 'favorite'].includes(msg.type)).length;
          
        this.$message.success('删除成功')
      } catch (error) {
        console.error('删除消息失败:', error)
        this.$message.error('删除消息失败')
      }
    },
    // 标记所有为已读
    async markAllAsRead() {
      try {
        // 确保userId存在且有效
        if (!this.userId) {
          console.error('用户ID未定义，无法标记全部已读');
          this.$message.error('用户信息未加载完成，请稍后重试');
          return;
        }

        await request({
          url: '/api/message/read-all',
          method: 'put',
          params: {
            userId: this.userId
          }
        })
        // 更新所有本地消息状态
        this.messages.forEach(message => {
          message.isRead = true
        })
        this.$message.success('已全部标记为已读')
      } catch (error) {
        console.error('标记全部已读失败:', error)
        this.$message.error('标记全部已读失败')
      }
    }
  }
}
</script>

<style scoped>
.box-card {
  margin: 20px;
}

.message-count {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background-color: #f56c6c;
  color: white;
  border-radius: 10px;
  padding: 0 6px;
  font-size: 12px;
  line-height: 18px;
}
</style>
